from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from tags.models import TaggedObject, TagType
from django.shortcuts import get_object_or_404

from django.core.cache import cache

@login_required #TODO: only allow file/asset owners to tag stuff
def add(request, content_type_id, object_id, tag_id):
  '''
  content_type = ContentType.objects.get(id=content_type_id)
  object = content_type.get_object_for_this_type(id=object_id)
  tag = get_object_or_404(TagType, id=tag_id)
  try:
    tagged_object = TaggedObject.objects.get(tag=tag, object_id=object_id, content_type=content_type)
    tagged_object.user = request.user
    tagged_object.save()
  except TaggedObject.DoesNotExist:
    rating_object = TaggedObject.objects.create(user=request.user, content_object=object, tag=tag)
  '''
  content_type = ContentType.objects.get(id=content_type_id)
  object = content_type.get_object_for_this_type(id=object_id)
  tag = get_object_or_404(TagType, id=tag_id)
  tagged_object = TaggedObject.objects.get_or_create(tag=tag, object_id=object_id, content_type=content_type, user=request.user)
  return HttpResponse(str(TaggedObject.objects.filter(object_id=object_id, content_type=content_type).count()))

@login_required
def remove(request, content_type_id, object_id, tag_id):
  TaggedObject.objects.filter(tag__id=tag_id, object_id=object_id, content_type__id=content_type_id, user=request.user).delete()

  return HttpResponse()
  

from assets.util import HttpResponseSerialized, Fields

def allTags():  
  data = []
  for m in TagType.objects.all().order_by():
    f = Fields(m, 'id', 'category', 'type')
    f['count'] = m.taggedobject_set.count()
    data.append(f)
  return data
  
def tags(request):  
  data = allTags()
  return HttpResponseSerialized(request, data)

from assets.models import Asset  
def asset_tags(request, as_id):  
  asset = get_object_or_404(Asset, id=as_id)

  from django.db.models import Avg, Max, Min, Count
  
  content_type = ContentType.objects.get_for_model(asset)
  
  data = []
  for m in TagType.objects.filter(taggedobject__content_type=content_type, taggedobject__object_id=asset.id).annotate(count=Count('taggedobject__user')):
    f = Fields(m, 'id', 'category', 'type', 'count')
    f['owner'] =  0 < m.taggedobject_set.filter(user=request.user).count() if request.user.is_authenticated() else False
    data.append(f)
    
  return HttpResponseSerialized(request, data)

'''
from tags.models import TagType

from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseNotFound
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from django.contrib.auth.decorators import permission_required


from assets.urls import default_path
from django.utils import simplejson

from django.views.decorators.cache import never_cache


#=====================================================
try:
    from functools import update_wrapper, wraps
except ImportError:
    from django.utils.functional import update_wrapper, wraps  # Python 2.4 fallback.

from django.utils.decorators import available_attrs

def permission_required2(perm):
  """
  """
  def decorator(view_func):
    def _wrapped_view(request, *args, **kwargs):
      if request.user.is_authenticated():
        if request.user.has_perm(perm):
          return view_func(request, *args, **kwargs)
        else:
          return HttpResponse("You don't have the permissions to do this!", status=403) #forbidden
      else:
        return HttpResponse("Not logged in!", status=401) #unauthorized
    return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
  return decorator
#======================================================


  



@permission_required2('assets.can_add_tag')
def add_tag(request, as_id):  
  asset = get_object_or_404(Asset, id=as_id)
  
  if request.method == 'POST':
    t = int(request.POST['tagType'])
    tag = get_object_or_404(TagType, id=t)
    asset.tags.add(tag)
    asset.save()
    return HttpResponse(status=201)
  else:
    response = HttpResponse(status=400)
    return response

@permission_required2('assets.can_remove_tag')
def remove_tag(request, as_id):  
  asset = get_object_or_404(Asset, id=as_id)
  
  if request.method == 'POST':
    t = int(request.POST['tagType'])
    tag = get_object_or_404(TagType, id=t)
    asset.tags.remove(tag)
    asset.save()
    return HttpResponse(status=204)
  else:
    response = HttpResponse(status=400)
    return response
'''
